package cn.flying.cloud.oauth.service.impl;

import javax.annotation.Resource;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.PageRequest;
import cn.flying.cloud.base.common.vo.PageResponse;
import cn.flying.cloud.oauth.entity.OauthClientDetail;
import cn.flying.cloud.oauth.mapper.OauthClientDetailMapper;
import cn.flying.cloud.oauth.service.OauthClientDetailService;

/**
 * 客户端信息服务类
 *
 * @author: admin
 * @date: 2023年04月11日 17:48
 * @version: 1.0
 */
@Service
public class OauthClientDetailServiceImpl extends ServiceImpl<OauthClientDetailMapper, OauthClientDetail> implements OauthClientDetailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Resource
    private PasswordEncoder passwordEncoder;


    /**
     * 分页查询客户端信息表数据
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<OauthClientDetail> page(PageRequest<OauthClientDetail> request) {
        OauthClientDetail param = request.getParam();
        LambdaQueryWrapper<OauthClientDetail> wrapper = getLambdaQueryWrapper(param);
        Page<OauthClientDetail> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()), wrapper);
        return new PageResponse<>(page.getTotal(), (int) page.getCurrent(), page.getRecords());
    }

    /**
     * 构建查询对象
     *
     * @param param
     * @return
     */
    private LambdaQueryWrapper<OauthClientDetail> getLambdaQueryWrapper(OauthClientDetail param) {
        LambdaQueryWrapper<OauthClientDetail> wrapper = new LambdaQueryWrapper<>();
        if (param != null) {
            if (Ft.String.isNotBlank(param.getClientId())) {
                wrapper.eq(OauthClientDetail::getClientId, param.getClientId());
            }
            if (!"10000".equals(param.getTenantId()) && !"10001".equals(param.getTenantId())) {
                if (Ft.String.isNotBlank(param.getTenantId())) {
                    wrapper.eq(OauthClientDetail::getTenantId, param.getTenantId());
                }
            }
            if (Ft.String.isNotBlank(param.getStatus())) {
                wrapper.eq(OauthClientDetail::getStatus, param.getStatus());
            }
        }
        return wrapper;
    }

    /**
     * 列表查询客户端信息表数据
     *
     * @param oauthClientDetail
     * @return
     */
    @Override
    public List<OauthClientDetail> list(OauthClientDetail oauthClientDetail) {
        LambdaQueryWrapper<OauthClientDetail> wrapper = getLambdaQueryWrapper(oauthClientDetail);
        List<OauthClientDetail> list = this.list(wrapper);
        return list;
    }

    /**
     * 查询客户端信息表详情数据
     *
     * @param oauthClientDetail
     * @return
     */
    @Override
    public OauthClientDetail detail(OauthClientDetail oauthClientDetail) {
        LambdaQueryWrapper<OauthClientDetail> wrapper = getLambdaQueryWrapper(oauthClientDetail);
        return this.getOne(wrapper);
    }


    /**
     * 新增客户端信息表数据
     *
     * @param clientDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean create(OauthClientDetail clientDetail) {
        clientDetail.setId(Ft.Snowflake.nextId());
        clientDetail.setClientId(UUID.randomUUID().toString().replaceAll("-", ""));
        clientDetail.setAppSecret(UUID.randomUUID().toString().replaceAll("-", ""));
        clientDetail.setClientSecret(passwordEncoder.encode(clientDetail.getAppSecret()));
//        clientDetail.setScope("all");
//        clientDetail.setResourceIds("");
//        clientDetail.setAuthorizedGrantTypes("authorization_code,password,client_credentials,implicit,refresh_token");
//        clientDetail.setWebServerRedirectUri("");
//        clientDetail.setAuthorities("");
//        clientDetail.setAccessTokenValidity(3600);
//        clientDetail.setRefreshTokenValidity(7200);
//        clientDetail.setAdditionalInformation("");
//        clientDetail.setAutoapprove("true");
//        clientDetail.setRemark("");
//        clientDetail.setCreatedBy("system");
//        clientDetail.setCreatedTime(LocalDateTime.now());
//        clientDetail.setUpdatedBy("system");
//        clientDetail.setUpdatedTime(LocalDateTime.now());
//        clientDetail.setTenantId("");
//        clientDetail.setRevision(0L);
//        clientDetail.setDeleted("");

        return this.save(clientDetail);
    }

    /**
     * 更新客户端信息表数据
     *
     * @param oauthClientDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(OauthClientDetail oauthClientDetail) {
        LambdaQueryWrapper<OauthClientDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OauthClientDetail::getClientId, oauthClientDetail.getClientId());
        OauthClientDetail clientDetail = this.getOne(wrapper);
        // 目前只更新uri
        clientDetail.setWebServerRedirectUri(oauthClientDetail.getWebServerRedirectUri());
        return this.saveOrUpdate(clientDetail);
    }

    /**
     * 删除客户端信息表数据
     *
     * @param oauthClientDetail
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(OauthClientDetail oauthClientDetail) {
        LambdaQueryWrapper<OauthClientDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OauthClientDetail::getClientId, oauthClientDetail.getClientId());
        return this.remove(wrapper);
    }
}
